//获取应用实例
const app = getApp()
// pages/order/orderTabs/orderTabs.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    token: "",
    baseImgUrl: getApp().globalData.IMG_URL,
    serverUrl: getApp().globalData.SERVER_URL,

    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    navData: [
      {
        text: '全部'
      },
      {
        text: '待付款'
      },
      {
        text: '待收货'
      },
      {
        text: '已收货'
      },
      {
        text: '售后/退货'
      },
      {
        text: '评价'
      },
    ],
    currentTab: 0,
    navScrollLeft: 0,

    orderAndGoodsList: Array,

    showLoading: true,
    showLoadingTxt: "努力加载中...",
    pageNo: 1,
    pageSize: 10,
    isRefresh: true,
    allPages: 0,

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          pixelRatio: res.pixelRatio,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      },
    })

    const token = wx.getStorageSync('token')
    const user = wx.getStorageSync('userInfo');
    // console.error(JSON.parse(user));
    this.setData({ userInfo: JSON.parse(user), token: token });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 查询用户订单
    this.setData({ pageNo: 1, isRefresh: true })
    this.getOrderHistoryPageForCurrUser(this.data.pageNo, this.data.pageSize)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  switchNav(event: any) {
    var cur = event.currentTarget.dataset.current;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 6;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
  },
  switchTab(event: any) {
    var cur = event.detail.current;
    var singleNavWidth = this.data.windowWidth / 5;
    this.setData({
      currentTab: cur,
      navScrollLeft: (cur - 2) * singleNavWidth
    });
  },

  // 加载数据
  getOrderHistoryPageForCurrUser(pageNum: number, pageSize: number): void {
    var that = this
    const url = this.data.serverUrl + "fc/emall/order/client/historyPageForCurrUser"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        pageNo: pageNum,
        pageSize: pageSize
      },
      header: {
        'content-type': 'application/json', // 默认值
        'X-Access-Token': this.data.token
      },
      success(res: any) {
        console.error("success ==> " + JSON.stringify(res.data))
        wx.stopPullDownRefresh() //wx.startPullDownRefresh()
        if (res.data.code == 200) {
          that.setData({ allPages: res.data.result.pages })
          console.info("total = " + res.data.result.total)
          console.info("allPages = " + res.data.result.pages)

          const length = res.data.result.records.length
          if (length > 0) {
            for (let index = 0; index < length; index++) {
              const item = res.data.result.records[index]
              if (item != null) {
                var goodsNum = 0
                for (let index = 0; index < item.goodsList.length; index++) {
                  const goods = item.goodsList[index];
                  goodsNum = goodsNum + goods.saleNum;
                  // 处理方面
                  const cover = goods.goodsCover;
                  const firstIndex = cover.indexOf(',');
                  const coverReal = cover.substring(0, firstIndex);
                  goods.goodsCover = coverReal
                }
                item.goodsListNum = goodsNum
              }
            }

            if (that.data.isRefresh) {// 刷新
              that.setData({ orderAndGoodsList: res.data.result.records })
              that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
            } else {// 加载更多
              that.setData({ orderAndGoodsList: that.data.orderAndGoodsList.concat(res.data.result.records) })
              that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
            }
            // console.error("加载更多：" + JSON.stringify(that.data.orderAndGoodsList))
          } else {
            if (that.data.isRefresh) {
              that.setData({ showLoading: true, showLoadingTxt: "暂无数据" })
            }
          }
        } else {
          console.info(JSON.stringify(res))
          that.setData({ showLoading: true, showLoadingTxt: res.data.msg })
        }
      },
      fail(err: any) {
        that.setData({ showLoading: true, showLoadingTxt: err.errMsg })
      }
    })
  },
})